package com.tairan.chapter.tio.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.starter.TioWebSocketServerBootstrap;

/**
 * @author litairan
 * @date 2019/9/27
 */
@RestController
@RequestMapping("/push")
public class PushController {

    @Autowired
    private TioWebSocketServerBootstrap bootstrap;

    @GetMapping("/{from}/{to}")
    public String pushMsg(@PathVariable String from,
                          @PathVariable String to,
                          String msg) {
        if (!StringUtils.hasLength(msg)) {
            msg = Math.random() + "";
        }
        String temp = "{name:'" + from + "',message:'" + msg + "'}";
        Tio.sendToUser(bootstrap.getServerTioConfig(), from, WsResponse.fromText(temp, "utf-8"));
        Tio.sendToUser(bootstrap.getServerTioConfig(), to, WsResponse.fromText(temp, "utf-8"));
        return "success";
    }
}
